<script setup lang="ts">
import { ref, computed, onMounted, watch } from "vue";
import { useSubmissionHook } from "@/views/cafuc/audit/auditList/utils/hook";
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { ElMessage, ElMessageBox } from "element-plus";

import Search from "@iconify-icons/ep/search";
import Refresh from "@iconify-icons/ep/refresh";
import { useUserStoreHook } from "@/store/modules/user";
import SubmissionDetailModal from "@/views/cafuc/submit/submission/submission-detail-modal.vue";
import SubmissionReviewModal from "./submission-review-modal.vue";
import View from "@iconify-icons/ep/view";
import { SubmissionPageResponse } from "@/api/performance/submission";
import Check from "@iconify-icons/ep/check";
import { getAllUsersSimpleApi, type UserSimpleDTO } from "@/api/system/user";
import { useRouter } from "vue-router";

/** 组件name最好和菜单表中的router_name一致 */
defineOptions({
  name: "submissionReview"
});

const router = useRouter();
const tableRef = ref();
const searchFormRef = ref();

// 获取当前用户信息
const userStore = useUserStoreHook();
const currentRoleId = computed(
  () => userStore.currentUserInfo?.roleId as number | undefined
);
const currentRoleName = computed(
  () => userStore.currentUserInfo?.roleName as string | undefined
);
const currentUserId = computed(
  () => userStore.currentUserInfo?.userId as number | undefined
);
const currentUserInfo = computed(() => userStore?.currentUserInfo);

// 个人信息完整性检查
const isProfileComplete = computed(() => {
  const user = currentUserInfo.value;
  // 检查真实姓名（可能是nickName或nickname）
  const hasNickName = !!(user?.nickName || (user as any)?.nickname);
  return !!(
    hasNickName &&
    user?.phoneNumber &&
    user?.deptId
  );
});

const {
  searchFormParams,
  pageLoading,
  columns,
  dataList,
  pagination,
  timeRange,
  defaultSort,
  multipleSelection,
  mainCategoryOptions,
  subCategoryOptions,
  itemCategoryOptions,
  onSearch,
  resetForm,
  onSortChanged,
  getSubmissionList,
  handleMainCategoryChange,
  handleSubCategoryChange,
  isSubProject,
} = useSubmissionHook({ autoFetch: false });

// 根据角色设置默认搜索条件
function setDefaultSearchConditions() {
  const roleId = currentRoleId.value;
  
  // 超级管理员不设置默认条件
  if (roleId === 1) {
    return;
  }
  
  // 设置默认状态为审核中
  searchFormParams.status = "PENDING_AUDIT";
  
  // 根据角色设置默认审核级别
  if ([3, 4, 5, 6].includes(Number(roleId))) {
    searchFormParams.currentAuditLevel = 1;
  } else if (roleId === 7) {
    searchFormParams.currentAuditLevel = 2;
  } else if (roleId === 8) {
    searchFormParams.currentAuditLevel = 3;
  }
  
  // 根据角色设置默认主类别
  // 3: 教学、科研教研一级审核 -> 科研工作量、教研工作量
  if (roleId === 3) {
    searchFormParams.mainCategory = "科研工作量;教研工作量";
  }
  // 4: 育人工作量一级审核 -> 育人工作量
  else if (roleId === 4) {
    searchFormParams.mainCategory = "育人工作量";
  }
  // 5: 服务与其他类工作量一级审核 -> 服务工作量 或 其他工作量
  else if (roleId === 5) {
    searchFormParams.mainCategory = "服务工作量;其他工作量";
    // 这里可以根据实际需求设置，暂时不设置，让用户选择
    // searchFormParams.mainCategory = "服务工作量";
  }
  // 6, 7, 8: 总一级、二级、三级审核 -> 不设置主类别限制
}

// 审核相关
const reviewModalVisible = ref(false);
const reviewRows = ref<SubmissionPageResponse[]>([]);

function openReviewDialog(row?: SubmissionPageResponse) {
  // 检查个人信息完整性
  if (!isProfileComplete.value) {
    ElMessageBox.confirm(
      "需要先补充个人信息才能使用此功能，是否前往个人中心？",
      "提示",
      {
        confirmButtonText: "前往",
        cancelButtonText: "取消",
        type: "warning"
      }
    )
      .then(() => {
        router.push("/global/user/profile");
      })
      .catch(() => {});
    return;
  }

  const reviewableStatuses = ["PENDING_AUDIT", "APPROVED"];

  if (row) {
    reviewRows.value = [row];
  } else {
    // 批量审核
    if (multipleSelection.value.length === 0) {
      ElMessage.warning("请选择需要审核的数据");
      return;
    }
    const selectedRows = dataList.value.filter(item => {
      return (
        multipleSelection.value.includes(item.id) &&
        reviewableStatuses.includes(item.status) &&
        !isSubProject(item)
      );
    });
    if (selectedRows.length === 0) {
      ElMessage.warning("请选择状态为'审核中'或'已批准'的数据");
      return;
    }
    reviewRows.value = selectedRows;
  }
  reviewModalVisible.value = true;
}

function handleSelectionChange(rows: SubmissionPageResponse[]) {
  multipleSelection.value = rows.map(item => item.id);
}

const allUsers = ref<UserSimpleDTO[]>([]);
const userOptions = ref<UserSimpleDTO[]>([]);

async function fetchAllUsersSimple() {
  try {
    const { data } = await getAllUsersSimpleApi();
    allUsers.value = data || [];
    userOptions.value = allUsers.value;
  } catch (e) {
    console.error(e);
  }
}

function remoteSearchUsers(query: string) {
  const q = (query || "").trim();
  if (!q) {
    userOptions.value = allUsers.value;
    return;
  }
  const lower = q.toLowerCase();
  userOptions.value = allUsers.value.filter(u =>
    (u.nickname || "").toLowerCase().includes(lower) ||
    (u.deptName || "").toLowerCase().includes(lower)
  );
}

function getUserLabel(u: UserSimpleDTO) {
  const name = u.nickname || "";
  const dept = u.deptName || "";
  return dept ? `${name}（${dept}）` : name;
}

const detailModalVisible = ref(false);
const detailRow = ref<SubmissionPageResponse>();
function openDetailDialog(row: SubmissionPageResponse) {
  detailRow.value = row;
  detailModalVisible.value = true;
}

// 定义审核级别选项
const auditLevelOptions = [
  { label: "非审核状态", value: 0 },
  { label: "待一审", value: 1 },
  { label: "待二审", value: 2 },
  { label: "待三审", value: 3 },
  { label: "已完成", value: 4 }
];

// 定义状态选项
const statusOptions = [
  { label: "待提交", value: "DRAFT" },
  { label: "审核中", value: "PENDING_AUDIT" },
  { label: "已驳回", value: "REJECTED" },
  { label: "已批准", value: "APPROVED" }
];

// 设置表格行的类名（用于标识项目负责人不等于得分人的行）
function getRowClassName({ row }: { row: SubmissionPageResponse }) {
  if (row.owner && row.creatorId && row.owner !== row.creatorId) {
    return "row-owner-different";
  }
  return "";
}

// 判断是否显示批量审核按钮
const showBatchReview = computed(() => {
  const roleId = currentRoleId.value;
  return [1, 6, 7, 8].includes(Number(roleId));
});

// 自定义重置函数
function handleReset() {
  resetForm(searchFormRef, tableRef);
}

onMounted(async () => {
  await fetchAllUsersSimple();
  setDefaultSearchConditions();
  getSubmissionList();
});
</script>

<template>
  <div class="main">
    <!-- 搜索栏 -->
    <el-form
      ref="searchFormRef"
      :inline="true"
      :model="searchFormParams"
      class="search-form bg-bg_color w-[99/100] pl-8 pt-[12px]"
    >
    <el-form-item label="序号" prop="title">
        <el-input
          v-model="searchFormParams.id"
          placeholder="请输入序号"
          clearable
          class="!w-[200px]"
        />
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="searchFormParams.title"
          placeholder="请输入标题"
          clearable
          class="!w-[200px]"
        />
      </el-form-item>
      <el-form-item label="考核年度" prop="assessmentYear">
        <el-input
          v-model="searchFormParams.assessmentYear"
          placeholder="请输入考核年度"
          clearable
          class="!w-[200px]"
        />
      </el-form-item>

      <!-- <el-form-item label="状态：" prop="status">
        <el-select
          v-model="searchFormParams.status"
          placeholder="请选择状态"
          clearable
          class="!w-[180px]"
          :disabled="currentRoleId !== 1"
        >
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item> -->

      <el-form-item label="主类别：" prop="mainCategory">
        <el-select
          v-model="searchFormParams.mainCategory"
          placeholder="请选择主类别"
          clearable
          class="!w-[180px]"
          :disabled="currentRoleId !== 1 && searchFormParams.mainCategory !== undefined"
          @change="handleMainCategoryChange"
        >
          <el-option
            v-for="item in mainCategoryOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="子类别：" prop="subCategory">
        <el-select
          v-model="searchFormParams.subCategory"
          placeholder="请选择子类别"
          clearable
          class="!w-[180px]"
          :disabled="!searchFormParams.mainCategory"
          @change="handleSubCategoryChange"
        >
          <el-option
            v-for="item in subCategoryOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="项目类别：" prop="itemCategory">
        <el-select
          v-model="searchFormParams.itemCategory"
          placeholder="请选择项目类别"
          clearable
          class="!w-[180px]"
          :disabled="!searchFormParams.subCategory"
        >
          <el-option
            v-for="item in itemCategoryOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <!-- <el-form-item label="当前审核级别" prop="currentAuditLevel">
        <el-select
          v-model="searchFormParams.currentAuditLevel"
          placeholder="请选择当前审核级别"
          clearable
          class="!w-[200px]"
          :disabled="currentRoleId !== 1 && searchFormParams.currentAuditLevel !== undefined"
        >
          <el-option
            v-for="item in auditLevelOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item> -->

      <el-form-item label="得分人" prop="owner">
        <el-select
          v-model="searchFormParams.owner"
          filterable
          remote
          reserve-keyword
          placeholder="搜索并选择用户"
          :remote-method="remoteSearchUsers"
          clearable
          class="!w-[200px]"
        >
          <el-option
            v-for="u in userOptions"
            :key="u.userId"
            :label="getUserLabel(u)"
            :value="u.userId"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          :icon="useRenderIcon(Search)"
          :loading="pageLoading"
          @click="onSearch(tableRef)"
        >
          搜索
        </el-button>
        <el-button
          :icon="useRenderIcon(Refresh)"
          @click="handleReset"
        >
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 提示信息 -->
    <el-alert
      type="info"
      :closable="false"
      show-icon
      style="margin-bottom: 12px;"
    >
      <template #default>
        <span>提示：多人参与的子项目无法编辑、删除、提交、审核，需要操作在主项目里操作，子项目会自动进行对应的修改。</span>
      </template>
    </el-alert>

    <!-- table bar 包裹  table -->
    <PureTableBar title="绩效审核列表" :columns="columns" @refresh="onSearch">
      <!-- 表格操作栏 -->
      <template #buttons>
        <el-button
          v-if="showBatchReview"
          type="primary"
          :icon="useRenderIcon(Check)"
          @click="openReviewDialog()"
        >
          批量审核
        </el-button>
      </template>
      <template v-slot="{ size, dynamicColumns }">
        <pure-table
          border
          ref="tableRef"
          align-whole="center"
          showOverflowTooltip
          table-layout="auto"
          :loading="pageLoading"
          :size="size"
          adaptive
          :data="dataList"
          :columns="dynamicColumns"
          :default-sort="defaultSort"
          :pagination="pagination"
          :paginationSmall="size === 'small' ? true : false"
          :row-class-name="getRowClassName"
          :header-cell-style="{
            background: 'var(--el-table-row-hover-bg-color)',
            color: 'var(--el-text-color-primary)'
          }"
          @page-size-change="getSubmissionList"
          @page-current-change="getSubmissionList"
          @sort-change="onSortChanged"
          @selection-change="handleSelectionChange"
        >
          <!-- 添加 title slot -->
          <template #title="{ row }">
            <el-button
              link
              type="primary"
              @click="openDetailDialog(row)"
            >
              {{ row.title }}
            </el-button>
          </template>
          <template #operation="{ row }">
            <!-- 子项目（项目负责人不等于得分人）不显示任何操作按钮 -->
            <template v-if="isSubProject(row)">
              <!-- 子项目不显示操作按钮 -->
            </template>
            <!-- 状态为审核中时，显示详情和审核按钮 -->
            <template v-else-if="row.status === 'PENDING_AUDIT'">
              <el-button
                class="reset-margin"
                link
                type="primary"
                :size="size"
                :icon="useRenderIcon(View)"
                @click="openDetailDialog(row)"
              >
                详情
              </el-button>
              <el-button
                class="reset-margin"
                link
                type="success"
                :size="size"
                :icon="useRenderIcon(Check)"
                @click="openReviewDialog(row)"
              >
                审核
              </el-button>
            </template>
            <!-- 其他状态仅显示详情 -->
            <el-button
              v-else
              class="reset-margin"
              link
              type="primary"
              :size="size"
              :icon="useRenderIcon(View)"
              @click="openDetailDialog(row)"
            >
              详情
            </el-button>
          </template>
        </pure-table>
      </template>
    </PureTableBar>

    <submission-detail-modal
      v-model="detailModalVisible"
      :row="detailRow"
    />

    <submission-review-modal
      v-model="reviewModalVisible"
      :rows="reviewRows"
      @success="getSubmissionList"
    />
  </div>
</template>

<style scoped lang="scss">
:deep(.el-dropdown-menu__item i) {
  margin: 0;
}

.search-form {
  :deep(.el-form-item) {
    margin-bottom: 12px;
  }
}
.score-summary-card {
  margin-bottom: 12px;

  :deep(.el-card__header) {
    font-weight: 600;
    font-size: 14px;
  }

  :deep(.el-descriptions__label) {
    font-weight: 500;
    color: var(--el-text-color-primary);
  }

  :deep(.el-descriptions__content) {
    font-weight: 600;
    color: var(--el-color-primary);
  }
}
// 去掉单元格两边的边框线
:deep(.el-table) {
  td {
    border-left: none !important;
    border-right: none !important;
  }
  
  th {
    border-left: none !important;
    border-right: none !important;
  }
}

// 项目负责人不等于得分人的行样式（灰色标识）
:deep(.row-owner-different) {
  background-color: rgba(158, 158, 158, 0.1) !important;
  
  &:hover {
    background-color: rgba(158, 158, 158, 0.15) !important;
  }
}
</style>

